import instance from '@/request/request'

export { REFRESH_TOKEN, PASS } from '../utils/constants.js'
import { getRefreshToken, removeRefreshToken, setAccessToken, setRefreshToken } from '@/utils/storage'
import { REFRESH_TOKEN } from '@/utils/constants'
import router from '@/router'

let flag = false // 设置开关，保证一次只能请求一次短token，防止客户多此操作，多次请求
const retryOldRequest = {
//维护失败请求的response
  requestQuery: [],
  //添加订阅者
  listen(response) {
    return new Promise((resolve) => {
      this.requestQuery.push((newToken) => {
        let config = response.config || {};
        config.headers['accessToken'] = newToken;
        resolve(instance(config));
      });
    });
  },

  //发布消息
  trigger(newToken) {
    this.requestQuery.forEach((fn) => {
      fn(newToken);
    });
    this.requestQuery = [];
  }
}


/*短token过期，携带token去重新请求token*/
export const refreshTokenMethod = (res) => {
  if (!flag) {
    flag = true
    let r_token = getRefreshToken() // 获取长token
    if (r_token) {
      const data = {
        userAccount: localStorage.getItem('profile-account'),
        refreshToken: r_token
      }
      instance({
        url: '/api/expert/refresh',
        method: 'post',
        data
      }).then( (result) => {
        if (result.code === 4006) {
          flag = false
          removeRefreshToken(REFRESH_TOKEN)
          //跳转首页
          router.push('/login')
        } else if (result.code === 200) {
          // 存储新的token
          setAccessToken(result.data.accessToken)
          setRefreshToken(result.data.refreshToken)
          flag = false
          // 重新请求数据
          retryOldRequest.trigger(result.data.accessToken)
        }
      })
      return retryOldRequest.listen(res)
    } else {
      //跳转首页
      router.push('/home')
    }
  }
}
